package com.glowdayz.glowmee.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import org.apache.log4j.Logger;

import com.glowdayz.common.DBHandler;
import com.glowdayz.common.DateTime;
import com.glowdayz.common.PageHandler;
import com.glowdayz.common.MultipartBox.FileInfo;
import com.glowdayz.glowmee.cmd.PouchProductMapCMD;

public class PouchProductMapDAO {
	
	static Logger logger = Logger.getLogger(PouchProductMapDAO.class);
	
	private static PouchProductMapDAO instance = null;
	
	DBHandler db = null;
	
	public static PouchProductMapDAO getInstance() {
		if (instance == null) {
			instance = new PouchProductMapDAO();
		}
		return instance;
	}
	
	public PouchProductMapDAO() {
		db = DBHandler.getInstance();
	}
	
	public int updateMappingProduct(int idPouchProduct, int product) throws SQLException {
		logger.debug("[updateMappingProduct] ---------- Method Start ----------");
		logger.debug("[updateMappingProduct][PARAM] idPouchProduct=" + idPouchProduct);
		logger.debug("[updateMappingProduct][PARAM] product=" + product);
		
		int result = 0;
		
		String sql = "UPDATE pouchproductmapping "
				+ "SET idProduct=?, isConfirm=1, modified_date=? "
				+ "WHERE idPouchProduct=?";
		PreparedStatement pstmt = db.getPrepareStatement(sql);
		
		try {
			pstmt.setInt(1, product);
			pstmt.setString(2, DateTime.getInstance().getNowDateTimeString());
			pstmt.setInt(3, idPouchProduct);
			
			DBHandler.getInstance().beginTrans();
			result = pstmt.executeUpdate();
			
			pstmt.close();
			pstmt = null;
		} catch (SQLException e) {
			DBHandler.getInstance().rollback();
			logger.error("[updateMappingProduct] " + e.getLocalizedMessage());
			logger.error("[updateMappingProduct] " + e.getSQLState());
		} finally {
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
		}
		
		if (result > 0) {
			DBHandler.getInstance().commit();
		} else {
			DBHandler.getInstance().rollback();
		}
		
		logger.debug("[updateMappingProduct][RETURN] result=" + result);
		logger.debug("[updateMappingProduct] ---------- Method End ----------");
		
		return result;
	}
	
	public PouchProductMapCMD getMappingProduct(int idPouchProduct) throws SQLException {
		logger.debug("[getMappingProduct] ---------- Method Start ----------");
		logger.debug("[getMappingProduct][PARAM] idPouchProduct=" + idPouchProduct);
		
		PouchProductMapCMD result = null;
		String sql = "SELECT m.idPouchProduct, m.idPouch, m.idRegister, r.nickName, m.requestText, m.create_date "
				+ "FROM pouchproductmapping m, pouch p, register r "
				+ "WHERE m.idPouch=p.idPouch AND p.idRegister=r.idRegister AND m.idPouchProduct=?";
		PreparedStatement pstmt = DBHandler.getInstance().getPrepareStatement(sql);
		
		try {
			pstmt.setInt(1, idPouchProduct);
			ResultSet rs = pstmt.executeQuery();
			
			if (rs != null) {
				if (rs.next()) {
					int num = rs.getInt(1);
					int idPouch = rs.getInt(2);
					int idRegister = rs.getInt(3);
					String nickName = rs.getString(4);
					String requestText = rs.getString(5);
					String create_date = rs.getString(6);
					
					if (idPouch == 1) {
						nickName = null;
					}
					
					FileInfo image = this.getImage(num);
					
					result = new PouchProductMapCMD(idPouchProduct, idRegister, nickName, requestText, create_date, image);
				}
				rs.close();
				rs = null;
			}
			pstmt.close();
			pstmt = null;
		} catch (SQLException e) {
			logger.error("[getMappingProduct] " + e.getLocalizedMessage());
			logger.error("[getMappingProduct] " + e.getSQLState());
		} finally {
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
		}
		
		if (result != null) {
			logger.debug("[getMappingProduct][RETURN] result=" + result.toString());
		}
		logger.debug("[getMappingProduct] ---------- Method End ----------");
		
		return result;
		
	}
	
	public ArrayList<PouchProductMapCMD> getRequestProductList(int page, int count, String order, String where) throws Exception {
		logger.debug("[getRequestProductList] ---------- Method Start ----------");
		logger.debug("[getRequestProductList][PARAM] page=" + page);
		logger.debug("[getRequestProductList][PARAM] count=" + count);
		logger.debug("[getRequestProductList][PARAM] order=" + order);
		logger.debug("[getRequestProductList][PARAM] where=" + where);
		
		ArrayList<PouchProductMapCMD> result = null;
		int cnt;
		if (where == null) {
			cnt = db.getCount("pouchproductmapping m, pouch p, register r", "*", "m.idPouch=p.idPouch AND p.idRegister=r.idRegister AND "
					+ "m.requestText is not null");
		} else {
			cnt = db.getCount("pouchproductmapping m, pouch p, register r", "*", "m.idPouch=p.idPouch AND p.idRegister=r.idRegister AND "
					+ "m.requestText is not null" + where);
		}
		
		if (count == -1) {
			count = cnt;
		}
		
		String sql = null;
		if (order == null && where == null) {
			sql = "SELECT m.idPouchProduct, m.idPouch, m.idRegister, r.nickName, m.requestText, m.isConfirm, m.create_date "
					+ "FROM pouchproductmapping m, pouch p, register r "
					+ "WHERE m.idPouch=p.idPouch AND p.idRegister=r.idRegister AND m.requestText is not null "
					+ "ORDER BY m.idPouchProduct DESC "
					+ "LIMIT ?, ?";
		} else if (order != null && where != null) {
			sql = "SELECT m.idPouchProduct, m.idPouch, m.idRegister, r.nickName, m.requestText, m.isConfirm, m.create_date "
					+ "FROM pouchproductmapping m, pouch p, register r "
					+ "WHERE m.idPouch=p.idPouch AND p.idRegister=r.idRegister AND m.requestText is not null" + where + " "
					+ "ORDER BY " + order + " "
					+ "LIMIT ?, ?";
		} else if (order != null) {
			sql = "SELECT m.idPouchProduct, m.idPouch, m.idRegister, r.nickName, m.requestText, m.isConfirm, m.create_date "
					+ "FROM pouchproductmapping m, pouch p, register r "
					+ "WHERE m.idPouch=p.idPouch AND p.idRegister=r.idRegister AND m.requestText is not null "
					+ "ORDER BY " + order + " "
					+ "LIMIT ?, ?";
		} else if (where != null) {
			sql = "SELECT m.idPouchProduct, m.idPouch, m.idRegister, r.nickName, m.requestText, m.isConfirm, m.create_date "
					+ "FROM pouchproductmapping m, pouch p, register r "
					+ "WHERE m.idPouch=p.idPouch AND p.idRegister=r.idRegister AND m.requestText is not null" + where + " "
					+ "ORDER BY m.idPouchProduct DESC "
					+ "LIMIT ?, ?";
		}
		
		PreparedStatement pstmt = DBHandler.getInstance().getPrepareStatement(sql);
		
		if (cnt == 0) {
			PageHandler.getInstance(page, cnt);
		} else {
			// 페이징 처리 --> 한 페이지에 count개씩, 페이지번호는 10개 출력
			PageHandler.getInstance(page, cnt, count, 10);
		}
		
		try {
			pstmt.setInt(1, PageHandler.getInstance().getStartRec());
			pstmt.setInt(2, PageHandler.getInstance().getPageArticleCount());
			ResultSet rs = pstmt.executeQuery();
			
			if (rs != null) {
				
				// SQL문장에 이상이 없을 경우에만 list 객체를 할당한다.
				// 이 객체가 null이라면 SQL실행에 실패한 경우이다.
				// 객체가 생성되지만, add()가 실행되지 않아서, size()값이 0이라면
				// 조건에 맞는 데이터가 없는 경우이다.
				result = new ArrayList<PouchProductMapCMD>();
				
				while(rs.next()) {
					int idPouchProduct = rs.getInt(1);
					int idPouch = rs.getInt(2);
					int idRegister = rs.getInt(3);
					String nickName = rs.getString(4);
					String requestText = rs.getString(5);
					int isConfirm = rs.getInt(6);
					String create_date = rs.getString(7);
					
					if (idPouch == 1) {
						nickName = null;
					}
					
					PouchProductMapCMD item = new PouchProductMapCMD(idPouchProduct, idRegister, nickName, requestText, isConfirm, create_date);
					result.add(item);
				}
				rs.close();
				rs = null;
			}
			pstmt.close();
			pstmt = null;
		} catch (SQLException e) {
			logger.error("[getRequestProductList] " + e.getLocalizedMessage());
			logger.error("[getRequestProductList] " + e.getSQLState());
		} finally {
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
		}
		
		if (result != null) {
			logger.debug("[getRequestProductList][RETURN] result_count=" + result.size());
		}
		logger.debug("[getRequestProductList] ---------- Method End ----------");
		
		return result;
	}
	
	public FileInfo getImage(int idx) throws SQLException {
		String fileSql = "SELECT fileOrgName, idAttacheFile, fileSaveName, fileDir, fileSize, fileType, sortKey "
				+ "FROM attachefile "
				+ "WHERE tableName='pouchproductmapping' AND tableKey=?";
		
		PreparedStatement pstmt = DBHandler.getInstance().getPrepareStatement(fileSql);
		FileInfo info = null;
		
		try {
			pstmt.setInt(1, idx);
			ResultSet rs = pstmt.executeQuery();
			if (rs != null) {
				while(rs.next()) {
					String fileOrgName = rs.getString(1);
					int idAttacheFile = rs.getInt(2);
					String fileSaveName = rs.getString(3);
					String fileDir = rs.getString(4);
					int fileSize = rs.getInt(5);
					String fileType = rs.getString(6);
					int sortKey = rs.getInt(7);
					
					info = new FileInfo("", idAttacheFile, fileOrgName, fileSaveName, fileDir, fileSize, fileType, sortKey);
				}
				rs.close();
				rs = null;
			}
			pstmt.close();
			pstmt = null;
		} catch (SQLException e) {
			logger.error(e.getLocalizedMessage());
			logger.error(e.getSQLState());
		} finally {
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
		}
		return info;
	}
	
}
